<template>
  <Panel :padding="10">
    <div slot="title">总成绩分析</div>
    <!-- 总成绩分析图 -->
    <div id="totalScoreAnalysis"></div>
    <!-- 搜索，下载 -->
    <el-row :gutter="20">
      <el-col :span="8" :offset="12">
        <el-input
          v-model="keyword"
          prefix-icon="el-icon-search"
          placeholder="关键词">
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click.native="downloadCSV()" icon="el-icon-download">下载</el-button>
      </el-col>
    </el-row>
    <!-- 总成绩表 -->
    <el-table
      v-loading="loading"
      element-loading-text="加载中"
      ref="table"
      :data="tableData"
      id="totalScoreTable">
      <el-table-column
        prop="id"
        width="60"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="classes"
        label="班级">
      </el-table-column>
      <el-table-column
        prop="username"
        label="学号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="realname"
        label="姓名">
      </el-table-column>
      <el-table-column
        v-for="(h, index) in homeworks" :key="h.id"
        :prop="h.id"
        :label="h.id">
        <template slot-scope="scope">
          {{ scope.row.homeworks[index].score }}
        </template>
      </el-table-column>
      <el-table-column
        prop="total"
        label="总成绩">
        <template slot-scope="scope">
          {{ scope.row.total }}
        </template>
      </el-table-column>
      <el-table-column
        prop="totalPercents"
        label="百分制总成绩">
        <template slot-scope="scope">
          {{ scope.row.totalPercents }}
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="panel-options">
      <el-pagination
        class="page"
        layout="prev, pager, next"
        @current-change="currentChange"
        :page-size="pageSize"
        :total="total">
      </el-pagination>
    </div> -->
  </Panel>
</template>

<script>
  import Echarts from 'echarts'
  import api from '../../api.js'
  import Pagination from '@oj/components/Pagination'
  export default {
    name: 'classroom-data-analysis',
    components: {
      Pagination
    },
    data () {
      return {
        totalScoreAnalysis: null,
        options: {},
        keyword: '',
        loading: true,
        data: {
          students: [],
          homeworks: []
        },
        tableData: [],
        homeworks: [], // 表格中加载的作业
        submissions: [],
        xAxisData: [],
        yAxisData: [],
        totalHomeworkScore: 0,
        currentBarName: '',
        className: ''
      }
    },
    mounted () {
      this.loadAllStudentsData()
    },
    methods: {
      loadAllStudentsData () {
        // 先加载全部学生
        api['getClassroom'](this.$route.params.classroomId).then(res => {
          this.className = res.data.data.name
          res.data.data.students.forEach(student => {
            this.data.students.push({
              id: student.id,
              classes: student.classes,
              username: student.user.username,
              realname: student.real_name
            })
          })
        })
        // 加载全部作业
        api['getCourseHomeworks'](this.$route.params.courseId).then(res => {
          let id = 1
          res.data.data.forEach(hw => {
            // 加载表格中的全部作业, 并计算全部作业的总成绩
            this.homeworks.push({
              id: id.toString(),
              hwid: hw.id,
              title: hw.title,
              score: parseInt(hw.score)
            })
            id++
            this.totalHomeworkScore += parseInt(hw.score)
          })
        })
        // 所有学生的submissions
        api['getClassroomStudentsHomeworks'](this.$route.params.classroomId).then(res => {
          res.data.data.forEach(sub => {
            this.submissions.push({
              studentId: sub.student.id,
              homeworkId: sub.homework.id,
              homeworkTitle: sub.homework.title,
              score: parseInt(sub.score)
            })
          })
          this.submissions.reverse() // 倒序提交数据，最新的成绩会最后被加载，显示出来的就是最新的成绩
          this.getClassroomData()
        })
      },
      getClassroomData () {
        // 处理学生作业成绩
        this.data.students.forEach(student => {
          student.total = 0
          // 深拷贝课程全部作业给学生
          let tmp = JSON.stringify(this.homeworks)
          student.homeworks = JSON.parse(tmp)
          // 拿到学生作业的分数(user_id, classroom_id)
          let studentScores = []
          this.submissions.forEach(sub => {
            if (student.id === sub.studentId) {
              studentScores.push(sub)
            }
          })
          student.homeworks.forEach((h, index) => {
            // 设置默认成绩为0(包括缺考)
            h.score = 0
            // 加载真实作业分数
            studentScores.forEach((sub, index) => {
              if (sub.homeworkId === h.hwid) {
                h.score = sub.score
              }
            })
            // 计算学生总成绩
            student.total += h.score // 总分
            student.totalPercents = (student.total / this.totalHomeworkScore * 100).toFixed(0) // 百分制成绩
          })
        })
        // 计算x轴，百分制，计算分数范围
        this.xAxisData = [0, 30, 40, 50, 60, 70, 80, 90, 100]
        let scoreRanges = []
        for (let i = 0; i < 8; i++) {
          scoreRanges.push(this.xAxisData[i] + ' ~ ' + this.xAxisData[i + 1])
        }
        // 计算每档的学生人数
        let studentNo = new Array(this.xAxisData.length - 1) // 新建与档数相同的数组
        studentNo.fill(0) // 赋值为0
        this.data.students.forEach(student => {
          if (parseInt(student.totalPercents) === 100) {
            studentNo[studentNo.length - 1]++
            return
          }
          let i = 0
          while (i < this.xAxisData.length) {
            if (student.totalPercents < this.xAxisData[i]) {
              studentNo[i - 1]++
              return
            }
            i++
          }
        })
        // 拼接y轴数据
        for (let i = 0; i < 8; i++) {
          this.yAxisData.push({
            value: studentNo[i],
            scoreRange: scoreRanges[i]
          })
        }
        this.loading = false
        this.tableData = this.data.students
        this.drawLine()
      },
      // 初始化柱状图
      drawLine () {
        this.totalScoreAnalysis = Echarts.init(document.getElementById('totalScoreAnalysis'))
        // 深拷贝x轴数据，制作显示出来的x轴
        let tmp = JSON.stringify(this.xAxisData)
        let showxAxis = JSON.parse(tmp)
        showxAxis.pop()
        // 配置柱状图的信息
        this.barChartSetOptions(showxAxis)
        // 柱状图的点击事件
        this.totalScoreAnalysis.on('click', params => {
          // 获取当前柱的名字，改变颜色
          this.currentBarName = params.name
          this.barChartSetOptions(showxAxis)
          // 如果是默认颜色，就筛选数据；否则，显示全部数据
          if (params.color === '#495060') {
            this.tableData = []
            let low = params.data.scoreRange.split(' ~ ')[0]
            let high = params.data.scoreRange.split(' ~ ')[1]
            this.data.students.forEach(student => {
              if (student.totalPercents >= low && student.totalPercents < high) {
                this.tableData.push(student)
              }
              // 得满分的情况
              if (student.totalPercents === high) {
                this.tableData.push(student)
              }
            })
          } else {
            this.currentBarName = '' // 修改当前柱的名字为空，恢复默认颜色
            this.barChartSetOptions(showxAxis)
            this.tableData = this.data.students // 表格显示全部数据
          }
        })
      },
      // 柱状图的配置信息
      barChartSetOptions (showxAxis) {
        this.totalScoreAnalysis.setOption({
          tooltip: {
            formatter (params) {
              return '分数段：' + params.data.scoreRange + '<br> 人数: ' + params.data.value
            }
          },
          xAxis: [{
            type: 'category',
            data: showxAxis, // 少最后一个数据
            show: false
          },
          {
            type: 'category',
            data: this.xAxisData,
            boundaryGap: false,
            axisTick: { alignWithLabel: true },
            position: 'bottom'
          }],
          yAxis: {
            type: 'value',
            minInterval: 1
          },
          series: [{
            data: this.yAxisData,
            type: 'bar',
            itemStyle: {
              normal: {
                color: params => {
                  if (this.currentBarName === params.name) {
                    return '#a90000'
                  } else {
                    return '#495060'
                  }
                }
              }
            }
          }]
        })
      },
      // 下载表格信息
      downloadCSV () {
        const _self = this
        let tHeader = ['序号', '班级', '学号', '姓名']
        let filterVal = ['id', 'classes', 'username', 'realname']
        // 深拷贝x轴数据，制作显示出来的x轴
        let tmp = JSON.stringify(_self.tableData)
        let list = JSON.parse(tmp)
        // 加载表头和筛选数据的作业相关信息
        this.homeworks.forEach(homework => {
          tHeader.push(homework.id)
          filterVal.push(homework.id)
        })
        // 动态添加每个学生每份作业的分数
        list.forEach(student => {
          student.homeworks.forEach(homework => {
            student[homework.id] = homework.score
          })
        })
        // 加载表头和筛选数据的总成绩信息
        tHeader.push('总成绩', '百分制总成绩')
        filterVal.push('total', 'totalPercents')
        let jsonData = {
          score: {
            tHeader: tHeader,
            filterVal: filterVal,
            list: list
          }
        }
        _self.exportPathMethod(jsonData) // 调用exportPathMethod对数据进行处理导出
        _self.exportShow = false
      },
      exportPathMethod (data) {
        // 要导出的json数据
        let mainLists = data.score // 主表
        // 数据处理
        let mainTitle = mainLists.tHeader
        let mainTitleForKey = mainLists.filterVal
        let mainList = mainLists.list
        let mainStr = []
        mainStr.push(mainTitle.join('\t,') + '\n') // 标题添加上换列转成字符串并存进数组
        for (let i = 0; i < mainList.length; i++) {
          let temp = []
          for (let j = 0; j < mainTitleForKey.length; j++) {
            temp.push(mainList[i][mainTitleForKey[j]]) // 根据过滤器拿出对应的值
          }
          mainStr.push(temp.join('\t,') + '\n') // 取出来的值加上逗号换列转字符串存数组
        }
        // 两个表数组转成字符串合并
        let merged = mainStr.join('')
        // 导出csv文件
        const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(merged)  // encodeURIComponent解决中文乱码
        // 通过创建a标签实现
        let link = document.createElement('a')
        link.href = uri
        // 对下载的文件命名
        link.download = `${this.className}学生成绩.csv`
        document.body.appendChild(link)
        link.click()
      }
    },
    watch: {
      'keyword' () {
        this.currentChange(1)
      }
    }
  }
</script>

<style scoped>
#totalScoreAnalysis {
  width: 100%;
  height: 400px;
}
#totalScoreTable {
  width: 100%;
  margin-top:30px;
}
</style>
